//加载后,便开始运行的方法
//通过this,把window对象传进去
(function(window){
    //站点地址抽出,方便变换站点的时候,全局更换(主要是ajax使用)
    window.App = {};
    window.loginData = {};
    var ua = navigator.userAgent.toUpperCase();
    App.IS_ANDROID = ua.indexOf('ANDROID') != -1;
    App.IS_IOS = ua.indexOf('IPHONE OS') != -1;
    // App.isIPHONE = ua.indexOf('IPHONE') != -1;
    App.IS_NATIVE = false;//(App.IS_ANDROID || App.IS_IOS) ? true : false;
    App.severUrl = "/";
    App.urlList = {
        "getOrderInfo":"cashier/q/getOrderInfo.json",
        "resendSms":"cashier/q/paymentSubmitJson.json",
        "checkBankCard":"cashier/q/checkCardBin.json",
        "pay":"cashier/q/waitResultJson.json",
        "getPayStatus":"cashier/q/queryPayResult.json",
        "recvOrder":"cashier/q/recvOrder.json",    //client下单
        "getMerchantInfo":"cashier/q/getMerchantInfo.json",    //client获取商户信息
        "wxPay":"cashier/q/wxPay.json",


        "test":"cashier-wap/do/test.do",
        "getOrderInfoTest":"cashier-wap/do/getOrderInfo.do",
        "checkBankCardTest":"cashier-wap/do/checkBankCardTest.do",
        "resendSmsTest":"cashier-wap/do/resendSms.do",

        "getTokenInfo":"cashier/p/getTokenInfo.json",  //获取商户信息
        "queryCardBin":"cashier/p/queryCardBin.json", //卡bin查询
        "auth":"cashier/p/auth.json", //鉴权
        "authconfirm":"cashier/p/authconfirm.json", //鉴权确认
        "msgRetrySend":"cashier/p/msgRetrySend.json", //短信重发
        "queryAuthInfo":"cashier/p/queryAuthInfo.json", //查询绑卡信息 2017/11/02添加
        "queryBankList":"cashier/p/queryBankLimptPlaceByMember.json", //查询绑卡信息 2017/11/02添加

        "getMerInfo":"cashier/q/getMerInfo.json",
        "oneCodeRandomPay":"cashier/q/oneCodeRandomPay.json",

        "queryVoucherInfo":"cashier/p/queryVoucherInfo.json",
        "quickPayOrder":"cashier/p/quickPayOrder.json",
        "quickPayConfirm":"cashier/p/quickPayConfirm.json",
        "unbundCardBySms":"cashier/p/unbundCardBySms.json",
        "unbundSmsResend":"cashier/p/unbundSmsResend.json",
        "unbundCardBySmsConfirm":"cashier/p/unbundCardBySmsConfirm.json"
    };
    //添加  同盾设备指纹的对接 2017/12/05 start
    window.getTokenFun = function(){

        var tokenId = "yycjt-" +new Date().getTime() + "-"+ Math.random().toString(16).substr(2);
        _fmOpt = {
            partner: 'yycjt',
            appName: 'yycjt_web',
            token: tokenId
        };
        var cimg = new Image(1,1);
        cimg.onload = function() {
            _fmOpt.imgLoaded = true;
        };
        cimg.src = "https://fp.fraudmetrix.cn/fp/clear.png?partnerCode=yycjt&appName=yycjt_web&tokenId=" + _fmOpt.token;
        var fm = document.createElement('script'); fm.type = 'text/javascript'; fm.async = true;
        fm.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'static.fraudmetrix.cn/fm.js?ver=0.1&t=' + (new Date().getTime()/3600000).toFixed(0);
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(fm, s);
        document.cookie  = 'cashierRiskId='+ tokenId+";path=/";
    };
    //添加  同盾设备指纹的对接 2017/12/05 end
    //阻止click延迟点击效果
    App.unClick = function(){
        if($("#unClick").length>0){
            $("#unClick").show();
        }else{
            $("body").append('<div id="unClick"></div>');
        }
        setTimeout(function(){$("#unClick").hide();},400);
    };
    App.unFocus=function(){
        document.activeElement.blur();
    };
    window.objBlur=function(){
        document.activeElement.blur();
        $('input').blur();
    };
    window.back = function (options) {
        if (router && router.currentHash == "chooseInsurance") {
            if(wData.urlData.isNative){
                return false;
            }else{
                location.href = "index.html";
            }
        }else{
            router.back(options);
            return true;
        }
    };
    window.wLoading = {
        html : '<div class="shade"><div class="loading"><div class="loading_img"></div></div></div>',
        start : function(id){
            if($(".shade").length>0){
                $(".shade").show();
            }else{
                $("body").append(this.html);
            }
        },
        stop : function(id){
            $(".shade").hide();
        }
    };
    //追加date属性，返回本地时间的toJSON
    Date.prototype.toLocalJSON = function () {
        var day = this.getDate(),
            month = this.getMonth()+1,
            year = this.getFullYear();
        if(day<10){
            day = "0"+day;
        }
        if(month<10){
            month = "0"+month;
        }
        return year+"-"+month+"-"+day;
    }
    window.wTime = new function(){
        this.today = new Date();
        this.todayYMD = this.today.toLocalJSON();
        this.tomorrow = new Date(new Date().setDate(new Date().getDate() + 1));
        //当前时间的下一个整点
        var copyToday = this.today;
        copyToday.setHours(copyToday.getHours()+1);
        this.nextHour = copyToday.toLocalJSON()+" "+copyToday.toTimeString().slice(0,2)+":00:00";
        //明天的0点
        this.tomorrowBegin = this.tomorrow.toLocalJSON()+" 00:00:00";
        this.tomorrowYMD = this.tomorrow.toLocalJSON();
        this.tomorrowYMDH = this.tomorrow.toLocalJSON()+" "+this.tomorrow.toTimeString().slice(0,2)+":00:00";
        this.addDate = function(startDate,cycle,time){
            var start = new Date(startDate.slice(0,10));
            start.setHours(startDate.slice(11,13));
            var copyStart = start,
                time = Number(time),
                end;
            if(cycle == "d"){
                copyStart.setDate(start.getDate()+time);
            }else if(cycle == "y"){
                copyStart.setFullYear(copyStart.getFullYear()+time);
                copyStart.setDate(start.getDate()-1);
            }else if(cycle == "m"){
                copyStart.setMonth(copyStart.getMonth()+time);
            }
            end = copyStart.toLocalJSON()+" "+copyStart.toTimeString().slice(0,2)+":00:00";
            return end;
        }
    };

    window.wAjax = function(url,token,data,success,error,options,unload){
        //默认成功处理方式
        var wSuccess = function(data){
            !unload && wLoading.stop();
            if(success){
                typeof data == "string" && (data = JSON.parse(data));
                switch (data.resultCode){
                    case "995":
                    case "500":
                        wAlert("系统异常");
                        wLoading.stop();
                        break;
                    case "600":
                        wAlert("出错啦！"+data.errorMsg);
                        wLoading.stop();
                        break;
                    case "993":
                        wAlert("登录超时，请重新登录",function(){
                            resetWData();
                            wLoading.stop();
                            location.href = "index.html#operatorLogin";
                        });
                        break;
                    case "994":
                        wAlert(data.errorMsg,function(){
                            resetWData();
                            wLoading.stop();
                            location.hash = "index";
                        });
                        break;
                    case "997":
                        wAlert("交易超时啦，返回首页重新开始吧",function(){
                            resetWData();
                            wLoading.stop();
                            location.hash = "index";
                        });
                        break;
                    case "998":
                        wAlert("参数错误");
                        wLoading.stop();
                        break;
                    case "999":
                        wAlert("未知错误代码");
                        wLoading.stop();
                        break;
                    default :
                        success(data);
                }
            }else{

            }
        };
        var wError = function(data){
            !unload && wLoading.stop();
            if(error){
                error(data);
            }else{

            }
        };
        !unload && wLoading.start();
        var headersData = {},
            ajaxUrl = "";
        wData && wData.tid && (headersData.tid = wData.tid);
        wData && wData.uid && (headersData.uid = wData.uid);
        loginData && loginData.accToken && (headersData.accToken = loginData.accToken);
        if(url=="productId"){
            ajaxUrl = App.severUrl+App.urlList[url]+data+".json";
        }else if(url=="login") {
            ajaxUrl = App.severUrl+App.urlList[url]+"&loginId="+data.loginId+"&password="+data.password;
        }else if(url=="transactions") {
            ajaxUrl = App.severUrl+App.urlList[url]+"&userId="+data.userId;
        }else if(url=="transaction.do") {
            ajaxUrl = App.severUrl+App.urlList[url]+data.accToken+"/"+data.tid+".json";
        }else if(url=="transactionList") {
            ajaxUrl = App.severUrl+App.urlList[url]+"&userId="+data.userId+"&transDate="+data.transDate;
        }else{
            ajaxUrl = App.severUrl+App.urlList[url];
        }

        var ajaxOptions = {
            type:"post",
            url:ajaxUrl, //默认接口地址写死
            dataType:"json",
            data:JSON.stringify(data),
            headers:headersData,
            contentType:'application/json;charset=UTF-8',
            success:wSuccess,
            error:wError,
            beforeSend: function(request) {
                request.setRequestHeader("WxETopToken", token);
            }
        };
        _.extend(ajaxOptions,options);
        if(url =="cityCode"){delete ajaxOptions.data};
        $.ajax(ajaxOptions);
    };


    window.wAjaxForm = function(url,token,data,success,error,options,unload){
        //默认成功处理方式
        var wSuccess = function(data){
            !unload && wLoading.stop();
            if(success){
                success(data);
            }else{

            }
        };
        var wError = function(data){
            !unload && wLoading.stop();
            if(error){
                error(data);
            }else{

            }
        };
        !unload && wLoading.start();
        var headersData = {},
            ajaxUrl = "";
        wData && wData.tid && (headersData.tid = wData.tid);
        wData && wData.uid && (headersData.uid = wData.uid);
        loginData && loginData.accToken && (headersData.accToken = loginData.accToken);
        ajaxUrl = App.severUrl+App.urlList[url];
        var ajaxOptions = {
            type:"post",
            url:ajaxUrl, //默认接口地址写死
            dataType:"json",
            data:data,
            headers:headersData,
            contentType:'application/x-www-form-urlencoded;charset=UTF-8',
            success:wSuccess,
            error:wError,
            beforeSend: function(request) {
                request.setRequestHeader("WxETopToken", token);
            }
        };
        _.extend(ajaxOptions,options);
        if(url =="cityCode"){delete ajaxOptions.data};
        $.ajax(ajaxOptions);
    };

    window.wAjaxFormNoBg = function(url,token,data,success,error,options,unload){
        //默认成功处理方式
        var wSuccess = function(data){
            if(success){
                success(data);
            }else{

            }
        };
        var wError = function(data){
            if(error){
                error(data);
            }else{

            }
        };
        var headersData = {},
            ajaxUrl = "";
        wData && wData.tid && (headersData.tid = wData.tid);
        wData && wData.uid && (headersData.uid = wData.uid);
        loginData && loginData.accToken && (headersData.accToken = loginData.accToken);
        ajaxUrl = App.severUrl+App.urlList[url];
        var ajaxOptions = {
            type:"post",
            url:ajaxUrl, //默认接口地址写死
            dataType:"json",
            data:data,
            headers:headersData,
            contentType:'application/x-www-form-urlencoded;charset=UTF-8',
            success:wSuccess,
            error:wError,
            beforeSend: function(request) {
                request.setRequestHeader("WxETopToken", token);
            }
        };
        _.extend(ajaxOptions,options);
        if(url =="cityCode"){delete ajaxOptions.data}
        $.ajax(ajaxOptions);
    };

    window.wAjaxGet = function(url,token,data,success,error,options,unload){
        //默认成功处理方式
        var wSuccess = function(data){
            !unload && wLoading.stop();
            if(success){
                typeof data == "string" && (data = JSON.parse(data));
                switch (data.resultCode){
                    case "995":
                    case "500":
                        wAlert("系统异常");
                        wLoading.stop();
                        break;
                    case "600":
                        wAlert("出错啦！"+data.errorMsg);
                        wLoading.stop();
                        break;
                    case "993":
                        wAlert("登录超时，请重新登录",function(){
                            resetWData();
                            wLoading.stop();
                            location.href = "index.html#operatorLogin";
                        });
                        break;
                    case "994":
                        wAlert(data.errorMsg,function(){
                            resetWData();
                            wLoading.stop();
                            location.hash = "index";
                        });
                        break;
                    case "997":
                        wAlert("交易超时啦，返回首页重新开始吧",function(){
                            resetWData();
                            wLoading.stop();
                            location.hash = "index";
                        });
                        break;
                    case "998":
                        wAlert("参数错误");
                        wLoading.stop();
                        break;
                    case "999":
                        wAlert("未知错误代码");
                        wLoading.stop();
                        break;
                    default :
                        success(data);
                }
            }else{

            }
        };
        var wError = function(data){
            !unload && wLoading.stop();
            if(error){
                error(data);
            }else{

            }
        };
        !unload && wLoading.start();
        var headersData = {},
            ajaxUrl = "";
        wData && wData.tid && (headersData.tid = wData.tid);
        wData && wData.uid && (headersData.uid = wData.uid);
        loginData && loginData.accToken && (headersData.accToken = loginData.accToken);
        if(url=="productId"){
            ajaxUrl = App.severUrl+App.urlList[url]+data+".json";
        }else if(url=="transaction") {
            ajaxUrl = App.severUrl+App.urlList[url]+data.accToken+"/"+data.tid+".json";
        }else{
            ajaxUrl = App.severUrl+App.urlList[url];
        }

        var ajaxOptions = {
            type:"get",
            url:ajaxUrl, //默认接口地址写死
            dataType:"json",
            data:JSON.stringify(data),
            headers:headersData,
            contentType:'application/json;charset=UTF-8',
            success:wSuccess,
            error:wError,
            beforeSend: function(request) {
                request.setRequestHeader("WxETopToken", token);
            }
        };
        _.extend(ajaxOptions,options);
        if(url =="cityCode"){delete ajaxOptions.data};
        $.ajax(ajaxOptions);
    };
    window.wTips = function(text,auto){
        var html = "",
            $wTips = $("#wTips"),
            $wTipsText = $("#wTipsText");
        if(typeof text !="string"){
            $.each(text,function(key,value){
                html+="<p>"+value+"</p>";
            });
        }else{
            html = text;
        }
        if($wTips.length >0){
            $wTipsText.html(html);
            $wTips.show();
            if(auto !=false){
                setTimeout(function(){$wTips.hide()},3000);
            }
        }else{
            html ='<div id="wTips"><div id="wTipsText">'+html+'</div></div>',
                $body = $("body");
            $body.append(html);
            var $wTips = $("#wTips");
            $wTips.on("tap click",function(e){
                $wTips.hide();
            });
            if(auto !=false){
                setTimeout(function(){$wTips.hide()},3000);
            }
        }

    };
    window.wTextChange=function(str,number,endNumber,middleNumber){
        if(str!=undefined&&str!=null&&str!=""){
            var str1=str.substring(0,number);
            var str2=str.substring(str.length-endNumber,str.length);
            var returnStr=str1;
            var middle=str.length-endNumber-number;
            if(middleNumber!=undefined&&middleNumber!=null&&middleNumber!=""){
                middle=middleNumber;
            }
            for(var i=0;i<middle;i++){
                returnStr=returnStr+"*";
            }
            return returnStr+str2;
        }else{
            return ""
        }
    };
    window.wToAmount=function(str){
        str=str.toString();
        if(str==null||str==""||str==undefined){
            return "0.00";
        }else if(str.length==1){
            return "0.0"+str;
        }else if(str.length==2){
            return "0."+str;
        }else{
            str=str.toString();
            var strM="."+str.substring(str.length-2,str.length);
            str=str.substring(0,str.length-2);
            while(str.length>3){
                strM=","+str.substring(str.length-3,str.length)+strM;
                str=str.substring(0,str.length-3);
            }
            return str+strM;
        }
    };

    window.wTextBreak=function(str,num,direction){
        //direction    1:前->后,0:后->前
        var strM="";
        if(direction==1){
            while(str.length>num){
                strM=strM+str.substring(0,num)+" ";
                str=str.substring(num,str.length);
            }
            return strM+str
        }else{
            while(str.length>num){
                strM=" "+str.substring(str.length-num,str.length)+strM;
                str=str.substring(0,str.length-num);
            }
            return str+strM;
        }
    };

    window.wCheckBool=function(str,regular,msg,name){
        if(str==null||str==""||str==undefined){
            wTips(name+"不能为空");
            return false;
        }else if(regular==""){
            return true;
        }else{
            var Reg=new RegExp(regular);
            if(Reg.test(str)){
                return true;
            }else if(msg!=""){
                wTips(msg);
                return false;
            }else{
                wTips(name+"格式错误");
                return false;
            }
        }
    };
    window.wAlert = function(msg,callback,isConfirm,btn){
        var divHtml ="",
            msgHtml = "",
            pHtml = "",
            btn_sure = "确定",
            btn_cancel = "取消",
            callback = callback;
        btn && btn[0] && (btn_sure = btn[0]);
        btn && btn[1] && (btn_cancel = btn[1]);
        if(typeof(msg)=="string"){
            msgHtml = msg;
        }else{
            $.each(msg,function(key,value){
                msgHtml+="<p>"+value+"</p>";
            });
        }
        if(isConfirm){
            pHtml = '<p key="sure" class="border_right">'+btn_sure+'</p><p key="cancel" style="color:#9C9B9B;">'+btn_cancel+'</p>';
        }else{
            pHtml = '<p key="sure">'+btn_sure+'</p>';
        }
        if(!$("#maskLayer").length>0){
            divHtml = '<div class="maskLayer" id="maskLayer">' +
                '<div id="wAlert"><div id="wAlertText">'+msgHtml+'</div>' +
                '<div id="wAlertBtn">'+pHtml+'</div></div>' +
                '</div>';
            $("body").append(divHtml);
        }else{
            document.getElementById("wAlertText").innerHTML = msgHtml;
            document.getElementById("wAlertBtn").innerHTML = pHtml;
            document.getElementById("maskLayer").style.display ="block";
        }
        $("#wAlertBtn p").tap(function(e){
            var target = $(e.currentTarget),
                key = target.attr("key"),
                result = false;
            key=="sure" && (result = true);
            callback && callback(result);
            document.getElementById("maskLayer").style.display = "none";
            App.unClick();
        });
    };

    App.cookie = function (key, value, options) {
        var days, time, result, decode

        // A key and value were given. Set cookie.
        if (arguments.length > 1 && String(value) !== "[object Object]") {
            // Enforce object
            options = $.extend({}, options)

            if (value === null || value === undefined) options.expires = -1

            if (typeof options.expires === 'number') {
                days = (options.expires * 24 * 60 * 60 * 1000)
                time = options.expires = new Date()

                time.setTime(time.getTime() + days)
            }

            value = String(value)

            return (document.cookie = [
                encodeURIComponent(key), '=',
                options.raw ? value : encodeURIComponent(value),
                options.expires ? '; expires=' + options.expires.toUTCString() : '',
                options.path ? '; path=' + options.path : '',
                options.domain ? '; domain=' + options.domain : '',
                options.secure ? '; secure' : ''
            ].join(''))
        }

        // Key and possibly options given, get cookie
        options = value || {}

        decode = options.raw ? function (s) { return s } : decodeURIComponent

        return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null
    }
    /**
     * 获取URL参数
     * @return {String} name
     */
    App.getParams = function(options,callback){
        var callback = callback;
        if(options=="hash"){
            if(location.hash.indexOf("?")>=0){
                return location.hash.split("?")[0].replace("#","");
            }else{
                return location.hash.split("#")[1];
            }
        }
        if(location.href.split("?").length <2){
            return false;
        }
        var splitUrl = location.href.split("?"),
            urlArray = [],
            urlData={};
        if(splitUrl.length>=3){//地址栏有多组参数的情况
            urlArray = (splitUrl[1].split("#")[0]+"&"+splitUrl[2]).split("&");
        }else if(splitUrl[1].indexOf("#")>=0){//只有单组.html?数据的情况
            urlArray = splitUrl[1].split("#")[0].split("&");
        }else{//只有单组hash数据的情况
            urlArray = splitUrl[1].split("&");
        }
        $.each(urlArray,function(key,value){
            urlData[value.split("=")[0]] = decodeURI(value.split("=")[1]);
        });
        //把url参数的operator转到loginData ，url参数的获取基本上在大多数据处理的前面
        //其实想想，这个处理放在这里有点怪，而且还是在router里面调用的情景下，不放这里重新设计，好像也有点问题
        if(urlData.operator){
            loginData.operator = urlData.operator;
            delete urlData.operator;
        }
        if(urlData.accToken){
            loginData.accToken = urlData.accToken;
            delete urlData.accToken;
        }
        //如果没有acctoken，但有账号
        if(!loginData.accToken && loginData.operator){
            var operator_accToken_time = localStorage.operator_accToken_time;
            if(operator_accToken_time){
                var operatorArray = operator_accToken_time.split(","),
                    operator = operatorArray[0],
                    accToken = operatorArray[1],//之前的accToken
                    lastTime = operatorArray[2], //字符串反转，获取上一次的date
                    over24 = ((new Date().getTime() - lastTime)/1000/60/60) >0?false:true; //是否超过24小时
                if((loginData.operator == operator) && !over24){
                    loginData.accToken = accToken;
                }
            }
        }
        if(urlData.isNative)
        {
            App.IS_NATIVE =true;
        }
        return urlData;
    }
    getTokenFun();
})(this);


